package com.example.net.update

import android.app.IntentService
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import com.example.baseutils.*
import com.example.baseutils.application.BaseApplication
import com.example.net.oss.OSSUploader
import com.example.net.update.bean.VersionBean
import constant.UiType
import listener.UpdateDownloadListener
import model.UiConfig
import model.UpdateConfig
import update.UpdateAppUtils


class UpVersionService : IntentService("UpVersionService") {
    private val TAG = "UpVersionService"

    private val path = "version/branch/R3_college_update.json"

    private var versionBean: VersionBean? = null

    companion object {
        val VERSION_BROCATST = "VERSION_BROCATST"
        val UPDATE_BROCATST = "UPDATE_BROCATST"
        val VERSION = "version"
        val DONLOAD_PROGRESS = "progress"
        var isServiceRunning = false
        val SEPEECH_APP_TAG = "com.iflytek.speechcloud"
        val SEPEECH_APP_DOWN_URL = "https://imagecdn.didano.com/arpad/iflyttsfor7fter.apk"
        var realPath = "version/branch/fantacy_update.json"
        fun startUpVersionService(context: Context) {
            context.startService(Intent(context, UpVersionService::class.java))
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        "onStartCommand".log(TAG)
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onHandleIntent(intent: Intent?) {
        isServiceRunning = true

        var update = false
        "onHandleIntent wait 10s".log(TAG)
        //十秒后再检查更新版本
        TimeUtil.delayMs(10 * 1000)
        "onHandleIntent getAppVersion".log(TAG)

        initVersion()?.let {
            update = doUpadate(it.version, it.details, it.url)
        }
        if (!update) {
            val pkgListNew = AppUtils.getPkgListNew()
//            if (!pkgListNew.contains(Constance.TALKBACK_APP_TAG)) {
//                downAdnInstall(
//                    Constance.TALKBACK_APP_DOWN_URL, "下载语音组件",
//                    "下载tts语音组件 talkback，并安装。" +
//                            "\r\n请安装成功后到,设置，无障碍,查看是否有talkback。" +
//                            "\r\n安装完成后，请关掉应用，并手动重启app生效！", false
//                )
//            }
            if (Build.DEVICE == "rk3288" && !pkgListNew.contains(Constance.SEPEECH_APP_TAG)) {
                downAdnInstall(
                    Constance.SEPEECH_APP_DOWN_URL, "下载语音中文语音tts引擎",
                    "下载中文引擎，并安装。" +
                            "\r\n请安装成功后到,设置,无障碍,talkback，右侧设置，文字转语音设置，选择设置tts发音引擎为 科大讯飞3.0。" +
                            "\r\n安装完成后，请关掉应用，并手动重启app生效！", false
                )
            }
        }


    }

    private fun initVersion(): VersionBean? {
        //创建下载器
        val ossUploader = OSSUploader(this)
        //传入要下载的文件路径
        versionBean =
            ossUploader.streamDownloadObject(realPath, VersionBean::class.java)
        "versionBean $versionBean".log(TAG)
        if (versionBean == null || versionBean?.version
                .equals(AppUtils.getAppVersionName(this))
        ) {
            Log.i(TAG, "无升级版本可用,无需升级 ")
            return null
        }
        Log.i(TAG, "versionBean: " + versionBean.toString())

//        val intent = Intent()
//        intent.action = VERSION_BROCATST
//        intent.putExtra(VERSION,
//            "发现新版本 v" + versionBean?.getVersion().toString() + " 点击安装"
//        )
//        sendBroadcast(intent)
        return versionBean
    }

    /*执行更新操作*/
    private fun doUpadate(versionName: String, versionDetails: String, urlPath: String): Boolean {
        val versionCompare = versionName.compareTo(AppUtils.getAppVersionName(this))
        if (versionCompare == 0) {
            "版本一致，无需升级".log(TAG)
            //先删除上一次的下载
//            UpdateAppUtils.getInstance().deleteInstalledApk()
            FileUtil.deleteDownFile(Constance.APK_DIR)
            return false
        }

        if (versionCompare < 0) {
            sendBroadcast(Intent().apply {
                action = (VERSION_BROCATST)
                putExtra("progress", "即将降级")
            })
        }
        var autoUpdata = false
        Log.e(TAG, "urlPath :$urlPath")
        if (urlPath.contains("auto")) {
            Log.e(TAG, "自动升级")
            autoUpdata = true
        }
        "开始升级 $versionName".log(TAG)

        downAdnInstall(urlPath, versionName, versionDetails, autoUpdata)
        return true

    }


    private fun downAdnInstall(
        urlPath: String,
        title: String,
        versionDetails: String,
        autoUpdata: Boolean
    ) {
        //配置更新
        //更新配置
        val updateConfig = UpdateConfig()
        //更新栏的图标
        updateConfig.notifyImgRes = R.drawable.xiaonuo
        //服务器上的版本号
        updateConfig.serverVersionName = title
        //显示更新下载进度弹窗
        updateConfig.force = autoUpdata
        //保存位置
        updateConfig.apkSavePath = Constance.APK_DIR
        updateConfig.apkSaveName = title + "_" + DateUtils.getCurrentShortTime("HHmmss")
        updateConfig.isJustDownLoad = false
        //弹窗的UI配置
        val uiConfig = UiConfig()
        //简洁配置
        uiConfig.uiType = UiType.SIMPLE
        //开始更新
        UpdateAppUtils.getInstance()
            .apkUrl(urlPath)
            .updateTitle("检测到新版本： $title")
            .updateContent(versionDetails)
            .uiConfig(uiConfig)
            .updateConfig(updateConfig)
            .setUpdateDownloadListener(object : UpdateDownloadListener {
                override fun onDownload(progress: Int) {
                    "下载进度 $progress".log(TAG)
                    sendBroadcast(Intent().apply {
                        action = (VERSION_BROCATST)
                        putExtra("progress", "下载进度...$progress %")
                    })
                }

                override fun onError(e: Throwable) {
                    "下载版本失败 $title".showToast(BaseApplication.instance)
                    sendBroadcast(Intent().apply {
                        action = (VERSION_BROCATST)
                        putExtra("progress", "下载失败请重试!")
                    })
                }

                override fun onFinish() {
                    "下载版本 $title 完成".showToast(BaseApplication.instance)
                    sendBroadcast(Intent().apply {
                        action = (VERSION_BROCATST)
                        var result = "下载完成安装中"
                        putExtra("progress", result)
                    })


                }

                override fun onStart() {
                    "开始下载".log(TAG)
                }

            }).update(autoUpdata)
    }

    override fun onDestroy() {
        super.onDestroy()
        isServiceRunning = false
    }
}
